package com.fedorvlasov.lazylist;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.pricetag.googleproductsearch.GoogleShopPriceSearchResult;
import com.pricetag.pricetagandroid.R;

public class LazyAdapter extends ArrayAdapter<GoogleShopPriceSearchResult> {

	public LazyAdapter(Context context, int textViewResourceId, List<GoogleShopPriceSearchResult> d) {
		super(context, textViewResourceId, d);
		activity = (Activity)context;
		searchResultList = d;
		inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(activity.getApplicationContext());
	}

//	public LazyAdapter(Activity a, List<GoogleShopPriceSearchResult> d) {
//		activity = a;
//		searchResultList = d;
//		inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		imageLoader = new ImageLoader(activity.getApplicationContext());
//	}
	
	private Activity activity;
	private List<GoogleShopPriceSearchResult> searchResultList;
	private static LayoutInflater inflater = null;
	public ImageLoader imageLoader;

	

	public int getCount() {
		return searchResultList.size();
	}

	public GoogleShopPriceSearchResult getItem(int position) {
		return searchResultList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final View view = inflater.inflate(R.layout.item_lazy_list, null);

		final GoogleShopPriceSearchResult searchResult = searchResultList.get(position);

		TextView titleTextView = (TextView) view.findViewById(R.id.lazy_list_title);
		titleTextView.setText(searchResult.getTitle());

		TextView priceTextView = (TextView) view.findViewById(R.id.lazy_list_price);
		priceTextView.setText("CDN$ " + searchResult.getPrice());

		TextView availabilityTextView = (TextView) view.findViewById(R.id.lazy_list_availability);
		availabilityTextView.setText(searchResult.getAvailability());

		ImageView imageView = (ImageView) view.findViewById(R.id.lazy_list_image);
		imageLoader.DisplayImage(searchResult.getImage(), imageView);

		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (searchResult.getLink() != null) {
					view.setBackgroundColor(Color.LTGRAY);
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(searchResult.getLink()));
					activity.startActivity(browserIntent);
				}
			}

		});

		return view;
	}
}